<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <!-- 响应式布局 -->
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>图书列表</title>
        <link href="layui/css/layui.css" rel="stylesheet" />
    </head>
    <body>
        <h1 style="text-align: center; color: #1e9fff;">图书列表</h1>
        <div class="layui-container" style="margin-top: 20px;">
            <div class="layui-row">
                <div class="layui-col-md12">
                    <!-- search -->
                    <!-- 搜索 图书名称选择 -->
                    <form class="layui-form layui-row layui-col-space16">
                        <div class="layui-col-md2">
                            <div class="layui-input-wrap">
                                <div class="layui-input-prefix">
                                    <i class="layui-icon layui-icon-read"></i>
                                </div>
                                <input type="text" name="bookName" value="" placeholder="图书名称" class="layui-input"
                                    lay-affix="clear">
                            </div>
                        </div>
                        <!--搜索 category类别选择 -->
                        <div class="layui-col-md2">
                            <div class="layui-input-wrap">
                                <!-- <select name="interest" lay-filter="aihao">
                                    <option value=""></option>
                                    <option value="0">写作</option>
                                    <option value="1" selected>阅读</option>
                                    <option value="2">游戏</option>
                                    <option value="3">音乐</option>
                                    <option value="4">旅行</option>
                                </select> -->
                                <div id="search-category"></div>
                            </div>
                        </div>
                        <!-- 搜索 图书状态选择 -->
                        <div class="layui-col-md2">
                            <div class="layui-input-wrap">
                                <select name="status" lay-filter="status-filter">
                                    <option value="" selected>上架状态</option>
                                    <option value="0">下架</option>
                                    <option value="1">上架</option>

                                </select>
                            </div>
                        </div>
                        <!-- 搜索  创建日期范围 -->
                        <div class="layui-col-md3">
                            <div class="layui-input-wrap">
                                <input type="text" name="timeRange" class="layui-input" id="ID-laydate-range-datetime"
                                    placeholder="日期范围">
                            </div>
                        </div>

                        <div class="layui-btn-container layui-col-md3">
                            <button class="layui-btn" lay-submit lay-filter="search">搜索</button>
                            <button type="reset" id="reset" class="layui-btn layui-btn-primary">清空</button>
                        </div>
                    </form>

                    <table id="book-list-table" class="layui-hide" lay-filter="test"></table>
                </div>
            </div>

        </div>

        <script src="layui/layui.js"></script>
        <script src="js/xm-select.js"></script>
        <script>
            layui.use(function() {
                let table = layui.table;
                let layer = layui.layer;
                let laydate = layui.laydate;
                let form = layui.form;
                let $ = layui.$;

                // 搜索提交
                form.on('submit(search)', function(data) {
                    let field = data.field; // 获得表单字段
                    let time = field.timeRange;
                    if (time && time.length > 0) {
                        if (times && times.length == 2) {
                            field.start = times[0].trim()
                            field.end = times[1].trim()
                        }
                    }

                    //执行搜索重载
                    table.reload('book-list-table', {
                        page: {
                            curr: 1 // 重新从第 1 页开始
                        },
                        where: field // 搜索的字段
                    });
                    return false; // 阻止默认 form 跳转
                });
                //搜索栏 图书类别渲染
                //ajax 获取分类列表
                $.getJSON("http://192.168.142.128:8080/getCategoryList", function(rsp) {
                    if (rsp.code == 0) {
                        var demo1 = xmSelect.render({
                            el: '#search-category',
                            prop: {
                                name: 'categoryName',
                                value: 'categoryId'
                            },
                            name: 'categoryId',
                            filterable: true,
                            theme: {
                                color: '#0081ff'
                            },
                            data: rsp.data,
                        });

                        $('#reset').on('click', function() {
                            demo1.setValue([])
                            // let field = ''
                            // //执行搜索重载
                            // table.reload('book-list-table', {
                            //     page: {
                            //         curr: 1 // 重新从第 1 页开始
                            //     },
                            //     where: field // 搜索的字段
                            // });
                        })
                    } else {
                        layer.msg(rsp.msg)
                    }
                })


                //搜索栏 日期渲染
                // 日期时间范围
                laydate.render({
                    elem: '#ID-laydate-range-datetime',
                    type: 'datetime',
                    format: 'yyyy/MM/dd HH:mm:ss',
                    range: true
                });

                //顶部工具栏按钮事件操作
                table.on('toolbar(test)', function(obj) {
                    let event = obj.event
                    if (event === "add") {
                        layer.open({
                            title: "添加图书",
                            type: 2,
                            content: "book-add.html",
                            area: ['500px', '650px'],
                            closeBtn: 1,
                            end: function() {
                                table.reload('book-list-table')
                            }
                        })
                    } else if (event === "batchRemove") {
                        let id = obj.config.id
                        let checkStatus = table.checkStatus(id);
                        let selectList = checkStatus.data;
                        if (selectList && selectList.length == 0) {
                            layer.msg("没有选择要删除的数据")
                        } else {
                            layer.confirm('确定删除？', {
                                btn: ['确定', '取消'] //按钮
                            }, function(index) { //传入弹出层的index
                                let bookIdList = [];
                                for (let i = 0; i < selectList.length; ++i) {
                                    bookIdList.push(selectList[i].bookId)
                                }
                                //console.log(bookIdList)
                                $.ajax({
                                    type: "post",
                                    url: "http://192.168.142.128:8080/batchDeleteBook",
                                    data: JSON.stringify(bookIdList),
                                    contentType: "application/json",
                                    dataType: "json",
                                    success: function(rsp) {
                                        if (rsp.code == 0) {
                                            table.reload("book-list-table")
                                        } else {
                                            layer.msg(rsp.msg)
                                        }
                                    }
                                })
                                //关闭提示框
                                layer.close(index)
                            }, function() {
                                //layer.msg("用户取消", {icon: 0})
                            })
                        }
                        //console.log(checkStatus)
                    }
                })
                //工具列按钮事件操作
                table.on('tool(test)', function(obj) {
                    if (obj.event === "edit") {
                        //todo
                        layer.open({
                            title: "编辑图书",
                            type: 2,
                            content: "book-edit.html?categoryId=" + obj.data.categoryId +
                                "&currentState=" + obj.data.status,
                            area: ['500px', '650px'],
                            closeBtn: 1,
                            end: function() {
                                table.reload('book-list-table')
                            },
                            success: function(layero, index, that) {
                                //获取frame 的dom元素
                                var body = layer.getChildFrame('body', index);
                                //回显
                                body.find('#bookId').val(obj.data.bookId)
                                body.find('#bookName').val(obj.data.bookName)
                                body.find('#authorName').val(obj.data.authorName)
                                body.find('#price').val(obj.data.price)
                                body.find('#picUrl')[0].src =
                                    "http://192.168.142.128:8080" + obj.data.bookUrl
                                body.find('#createTime').val(obj.data.createTime)
                                body.find('#bookAddress').val(obj.data.bookAddress)
                                body.find('#bookUrl').val(obj.data.bookUrl)
                                // body.find('#categoryId').val(obj.data.categoryId)
                                // body.find('#currentState').val(obj.data.status)
                                //body.getParams(obj.data.categoryId,obj.data.status)
                            }
                        })
                    } else if (obj.event === 'remove') {
                        //二次确认
                        layer.confirm('确定删除？', {
                            btn: ['确定', '取消'] //按钮
                        }, function(index) { //传入弹出层的index
                            let bookId_ = obj.data.bookId;
                            $.getJSON("http://192.168.142.128:8080/deleteBook", {
                                bookId: bookId_
                            }, function(rsp) { //参数是响应
                                if (rsp.code == 0) { //删除成功
                                    table.reload('book-list-table');
                                } else {
                                    layer.msg("删除失败", {
                                        icon: 0
                                    })
                                }
                            })
                            //关闭提示框
                            layer.close(index)
                        }, function() {
                            //layer.msg("用户取消", {icon: 0})
                        })
                    }
                });

                table.render({
                    elem: "#book-list-table",
                    url: "http://192.168.142.128:8080/getBooksPage", //这里不要带参数
                    page: {
                        theme: "#1e9fff"
                    },
                    toolbar: `
                    <div>
                        <button type="button" lay-event="batchRemove" class="layui-btn layui-bg-red">批量删除</button>
                        <button type="button" lay-event="add" class="layui-btn layui-btn-normal">添加</button>
                    </div
                    `,
                    request: {
                        pageName: "pageNo",
                        limitName: "pageSize"
                    },
                    parseData: function(res) {
                        return {
                            "code": res.code,
                            "msg": res.msg,
                            "count": res.data.total,
                            "data": res.data.page
                        }
                    },
                    cols: [
                        [{
                                type: 'checkbox',
                                field: 'left'
                            },
                            {
                                title: "图书编号",
                                field: "bookId"
                            },
                            {
                                title: "图书名称",
                                field: "bookName"
                            },
                            {
                                title: "图书作者",
                                field: "authorName"
                            },
                            {
                                title: "图书分类",
                                // field: "categoryId"
                                templet: function(currentRowData) {
                                    return currentRowData.category.categoryName
                                }
                            },
                            {
                                title: "图书价格",
                                sort: true,
                                field: "price"
                            },
                            {
                                title: "是否上架",
                                // field: "status"，
                                templet: function(currentRowData) {
                                    return currentRowData.status == 0 ?
                                        '<span class="layui-badge layui-bg-black">下架</span>' :
                                        '<span class="layui-badge layui-bg-blue">上架</span>'
                                }
                            },
                            {
                                title: "创建时间",
                                field: "createTime"
                            },
                            {
                                title: "操作",
                                templet: function(currentRowData) {
                                    let s =
                                        '<button type="button" lay-event="edit" class="layui-btn layui-btn-sm layui-btn-normal">更新</button>'
                                    s += '  <button type="button" lay-event="remove" class="layui-btn layui-btn-sm layui-bg-orange">删除</button>'
                                    return s;
                                }
                            }
                        ]
                    ]
                })

            });
        </script>
    </body>
</html>